"use server"

import {ActionState, RegisterForm} from "@/lib/zod/types";
import {RegisterSchema} from "@/lib/zod/schema";
import db from "@/lib/db";
import {hmacEncode} from "@/lib/password";
import {dataUrlToFile} from "@/lib/server-utils";
import * as fs from "node:fs";
import * as Path from "node:path";

export const register = async (_state: ActionState<RegisterForm>, data: FormData) => {
    const entries = Object.fromEntries(data);
    const safeParse = RegisterSchema.safeParse(entries);
    if (!safeParse.success) {
        const errors = safeParse.error.flatten().fieldErrors;
        return {
            code: 402,
            msg: "校验失败",
            errors,
            input: {
                email: entries.email as string,
                password: entries.password as string,
                pwd: entries.pwd as string,
                sex: entries.sex as string,
                username: entries.username as string,
                image: entries.image as string
            }
        }
    }

    try {

        const {email,sex,username,password,image} = safeParse.data;

        const toFile = dataUrlToFile(image);
        if(!toFile){
            throw new Error("参数异常缺少头像");
        }
        const buffer = await toFile.arrayBuffer();
        const bytes =  Buffer.from(buffer);
        const bashPath = Path.join(process.cwd(),"public/image",);
        if (!fs.existsSync(bashPath)) {
            fs.mkdirSync(bashPath)
        }
        fs.writeFileSync(Path.join(bashPath,toFile.name),bytes);


        const pwd = hmacEncode(password, process.env.USER_LOGIN_PASSWORD_SECRET!);

        await db.users.create({
            data: {
                email: email,
                sex: sex,
                password: pwd,
                username: username,
                image:`/image/${toFile.name}`
            }
        });

        return {
            code:200,
            msg:"校验成功",
        };
    } catch (e) {
        console.error(e);

        return {
            code: 500,
            msg: e?.toString()??"fail",
            input: {
                email: entries.email as string,
                password: entries.password as string,
                pwd: entries.pwd as string,
                sex: entries.sex as string,
                username: entries.username as string,
                image: entries.image as string
            }
        }
    }


}